package com.xh.baselibrary.utils.net.ping;

import com.xh.baselibrary.log.XLog;
import com.xh.baselibrary.utils.CloseableUtils;
import com.xh.baselibrary.utils.net.PingWorker;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CmdPingPolicy implements IPingPolicy{
    private String TAG = CmdPingPolicy.class.getSimpleName();
    @Override
    public long ping(String host, int port) throws Exception {
        Process p=null;
        BufferedReader buf=null;
        long ret = -1;
        int status =-1;
        try {
            XLog.i(TAG,"ping start");
            p = Runtime.getRuntime().exec("/system/bin/ping -c 1 -W 1" + " " + host);
            buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String str;
            while ((str = buf.readLine())!= null){
                XLog.i(TAG,"connect read = "+str);
                if (str.contains("time=")){
                    String strParse = str.substring(str.indexOf("time=")+5,str.indexOf("ms")).replace(" ","");
                    ret = (long) Float.parseFloat(strParse);
                    return ret;
                }
            }
            XLog.i(TAG,"ping end");
            status = p.waitFor();
            XLog.i(TAG,"ping end waitFor status = "+status);
            if (status!=0){
                ret = PingWorker.CONNECT_TIMEOUT_RESULT;
            }
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }finally {
            CloseableUtils.close(buf);
            try {
                if (p != null) {
                    p.exitValue();
                }
            }catch (IllegalThreadStateException e){
                if (p != null) {
                    p.destroy();
                }
            }
        }
        return ret;
    }

    @Override
    public void close() {

    }
}
